import 'dart:io';
import 'dart:math';

import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/entity/pay_method/installment_model.dart';
import 'package:cbec_app/entity/pay_method/pay_type_model.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:cbec_app/utils/payment/unionpay_service.dart';
import 'package:flutter_union_pay/enum/union_pay_enum.dart';
import 'package:flutter_union_pay/union_pay.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

import '../../../components/app_conifg.dart';
import '../../../utils/payment/alipay_service.dart';

///收银台控制器
class CashierController extends BaseController {
  //  是否保税
  bool hasBonded = false;
  // 是否是华为pay
  bool isHuaweiPay = false;

  ///订单编号
  String orderSn = '';

  ///支付金额
  String price = '';

  ///剩余支付时间
  String cd = '';

  //支付方式
  List<PayTypeModel> payTypeList = [];

  //支付方式选中
  int paySelected = 0;

  PayTypeModel currentPayTypeModel = PayTypeModel(name: '', code: '', tag: '', hasInstallment: false, icon: '', expend: false); // 初始化时的默认值

  // 品牌支付
  PayTypeModel? brandPayTypeModel;

  //银行卡选中
  bool bankcardSelected = false;

  List<Installment> currentInstallment = [];

  int currentInstallmentSelected = 0;

  ///支付插件
  Fluwx fluwx = Fluwx();
  late Function(WeChatResponse) responseListener;

  bool isCard = false;

  @override
  void onInit() async {
    super.onInit();
    UmengCommonSdk.onPageStart('收银台');
    final bool hasBonded = Get.arguments['hasBonded'] ?? false; // 直接取布尔值
    orderSn = Get.parameters['sn']!;
    price = Get.parameters['price']!;
    cd = Get.parameters['cd'] ?? DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
    isCard = (Get.parameters['isCard'] ?? 'false') == 'true';
    brandPayTypeModel = await _getPaymentBrand();
    await getPayMethod();
    update();
    if (GetPlatform.isAndroid || GetPlatform.isIOS) {
      ///支付监听
      responseListener = (response) {
        if (response is WeChatPaymentResponse) {
          if (response.errCode == 0) {
            Tools.showToast('支付成功');
            Get.toNamed('${Routes.paySuccess}/?price=$price&paySelected=$paySelected');
          } else if (response.errCode == -1) {
            Tools.showToast(response.errStr!);
          } else {
            Tools.showToast('支付取消');
          }
        }
      };
      fluwx.addSubscriber(responseListener);

      // 注册云闪付支付结果监听
      UnionPayService.registerPayListener((result) {
        // 根据支付结果处理
        switch (result.status) {
          case PaymentStatus.SUCCESS:
            // 支付成功，跳转到支付成功页面
            Get.toNamed('${Routes.paySuccess}/?price=$price&paySelected=$paySelected');
            Tools.showToast('支付成功');
            break;

          case PaymentStatus.FAIL:
            // 支付失败，提示错误信息
            Tools.showToast('支付失败');
            break;

          case PaymentStatus.CANCEL:
            // 支付取消，提示用户
            Tools.showToast('支付取消');
            break;

          default:
            // 处理未知状态
            Tools.showToast('未知支付状态');
            break;
        }
      });
    }
  }

  //选银行卡
  void selectBankcard(bool selected) {
    bankcardSelected = false;
    update();
  }

  //选支付类型
  void selectPayType(int index) {
    paySelected = index;
    currentPayTypeModel = payTypeList[paySelected]; // 更新选中的支付方法
    currentInstallment = currentPayTypeModel.installment ?? [];
    update();
  }

  void updateExpend(int index) {
    for (int i = 0; i < payTypeList.length; i++) {
      final model = payTypeList[i];
      if (i == index) {
        model.expend = !model.expend;
      }
    }
    update();
  }

  @override
  void onClose() {
    super.onClose();
    if (GetPlatform.isAndroid || GetPlatform.isIOS) {
      fluwx.removeSubscriber(responseListener);
    }
    UmengCommonSdk.onPageEnd('收银台');
  }

  /// 获取支付方式
  Future<void> getPayMethod() async {
    try {
      final value = await Network.getPayMethod();
      logger.i('支付项 $value');

      // 确保 value 是 List 类型
      if (value is List) {
        // 将返回的数据转换为 List<PayType>
        payTypeList = value.map((item) {
          // 使用 PayType.fromJson 进行转换
          return PayTypeModel.fromJson(item as Map<String, dynamic>);
        }).toList();

        if (brandPayTypeModel != null) {
          print('brandPayTypeModel ===== ${brandPayTypeModel!.icon}');
          bool boolValue = (hasBonded == true && isHuaweiPay == false);
          if (!boolValue) {
            payTypeList.insert(0, brandPayTypeModel!);
          }
        }
        // 默认选中第一个支付方式
        if (payTypeList.isNotEmpty) {
          paySelected = 0;
          currentPayTypeModel = payTypeList[paySelected]; // 使用第一个元素作为默认值
        }

        logger.i('payTypeList ====== $payTypeList');
        update();
      } else {
        logger.e('返回的数据不是 List 类型');
      }
    } catch (e) {
      logger.e('获取支付方式时发生错误: $e');
      // 可以根据需要处理错误，比如提示用户
    }
  }

  Future<PayTypeModel?> _getPaymentBrand() async {
    final seType = await UnionPay.seBrandCode();
    print('seType ==== $seType');
    switch (seType) {
      case "02": // Samsung Pay
        return PayTypeModel(name: '三星Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'samsung_pay.png', expend: false);
      case "04": // Huawei Pay
        isHuaweiPay = true;
        return PayTypeModel(name: '华为Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'huawei_pay.png', expend: false);
      case "25": // Xiaomi/Redmi Pay
        return PayTypeModel(name: 'Mi Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'xiaomi_pay.png', expend: false);
      case "27": // Meizu Pay
        return PayTypeModel(name: 'Meizu Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'meizu_pay.png', expend: false);
      case "29": // OPPO Pay
        return PayTypeModel(name: 'OPPO Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'oppo_pay.png', expend: false);
      case "33": // vivo Pay
        return PayTypeModel(name: 'Vivo Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'vivo_pay.png', expend: false);
      case "-2000": // 苹果支付
        return PayTypeModel(name: 'Apple Pay', code: 'brand_pay', tag: '', hasInstallment: false, icon: 'apple_pay.png', expend: false);
      default: // 未定义品牌
        return null;
    }
  }

  void payCard() {
    Tools.showLoading();
    Map<String, dynamic> params = {};
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['paySn'] = orderSn;
    params['payWayCode'] = currentPayTypeModel.code;
    params['sid'] = AppData.sid;
    if (currentInstallment.isNotEmpty) {
      params['period'] = currentInstallment[currentInstallmentSelected].value;
    }

    Tools.showLoading();
    Network.payCard(params).then((value) {
      Tools.hideLoading();
      //唤起支付
      switch (currentPayTypeModel.code) {
        case 'wechat_pay':
          callWeChatPay(value['content']);
          break;
        case 'ali_pay':
          payWithAlipay(value['content']);
          break;
        case 'union_pay':
          callUnionPay(value['content']);
          break;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  void payOrder() {
    Map<String, dynamic> params = {};
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['paySn'] = orderSn;
    params['payWayCode'] = currentPayTypeModel.code == 'brand_pay' ? 'union_pay' : currentPayTypeModel.code;
    params['sid'] = AppData.sid;
    if (currentInstallment.isNotEmpty) {
      params['period'] = currentInstallment[currentInstallmentSelected].value;
    }
    Tools.showLoading();
    Network.payOrder(params).then((value) {
      Tools.hideLoading();
      //唤起支付
      switch (currentPayTypeModel.code) {
        case 'wechat_pay':
          callWeChatPay(value['content']);
          break;
        case 'ali_pay':
          payWithAlipay(value['content']);
          break;
        case 'union_pay':
          callUnionPay(value['content']);
        case 'brand_pay':
          final Map<String, dynamic> result = value['content'];
          UnionPay.sePay(tn: result['tn'], mode: PaymentEnv.PRODUCT, scheme: 'uppay.bdegopro.com');
          break;
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///支付订单
  void paySubmitOrder() {
    if (isCard) {
      payCard();
    } else {
      payOrder();
    }
  }

  ///唤起支付
  void callWeChatPay(Map<String, dynamic> result) async {
    if (GetPlatform.isIOS || GetPlatform.isAndroid) {
      bool isInstall = await fluwx.isWeChatInstalled;
      if (!isInstall) {
        Tools.showToast('请先安装微信');
        return;
      }
      fluwx.pay(
          which: Payment(
        appId: result['appid'],
        partnerId: result['partnerid'],
        prepayId: result['prepayid'],
        packageValue: result['package'],
        nonceStr: result['noncestr'],
        // 此处为 int 格式，如果后端返回的int格式则不需要进行额外处理
        timestamp: int.parse(result['timestamp']),
        sign: result['sign'],
      ));
    }
  }

  // 支付方法
  Future<void> payWithAlipay(String info) async {
    // 检查是否安装支付宝
    logger.i("走了没");

    bool isInstalled = await AlipayService.isAliPayHaveInstalled();
    if (!isInstalled) {
      Tools.showToast('暂不支持支付宝');
      return;
    }

    // 调用支付服务
    Map<String, dynamic> result = await AlipayService.startAlipay(info);

    logger.i("返回结果 $result");

    // 处理支付结果
    Map<String, String> handleResult = AlipayService.handlePaymentResult(result);

    String? message = handleResult['resultMessage'];

    if (handleResult['resultStatus'] == '9000') {
      Get.toNamed('${Routes.paySuccess}/?price=$price&paySelected=$paySelected');
    }
    logger.i("结果 $message");

    Tools.showToast(message!);
  }

  ///唤起云闪付支付
  callUnionPay(Map<String, dynamic> result) async {
    logger.i('走了没');

    // bool isInstalled =  UnionPayService.isInstalled(env: PaymentEnv.PRODUCT, merchantInfo: '');

    // if (!isInstalled) {
    // Tools.showToast('请先安装云闪付');
    // return;
    // }

    await UnionPayService.pay(env: PaymentEnv.PRODUCT, tn: result['tn'], scheme: 'uppay.bdegopro.com');
  }
}
